<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="300px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="节点名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入" class="gw-input-width-244" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button @click="submitForm" type="primary">确定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DatasetTypeApi, DatasetTypeVO } from '@/api/multiModel/datasettype'

/** prompt模板 表单 */
defineOptions({ name: 'TreeNodeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formType = ref('') // 表单的类型：create - 新增；update - 修改
let formData = ref<DatasetTypeVO>({
  id: undefined,
  name: '',
  parentId: undefined,
  level: 1
})
const formRules = reactive({
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

let actionNode = ref<Tree>()
const rootFlag = ref(true)
/** 打开弹窗 */
const open = async (type: string, data:Tree, flag:boolean) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '增加节点' : '修改节点名称'
  formType.value = type
  let { id, name, parentId, level } = data
  actionNode.value = data
  rootFlag.value = flag
  resetForm()
  formData.value = { 
    id,
    name: type === 'create' ? '' : name,
    parentId,
    level
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  try {
    const data = formData.value as unknown as DatasetTypeVO
    if (formType.value === 'create') {
      let params:any = {
        name: data.name,
        level: data.level + 1,
        parentId: data.id
      }
      const res = await DatasetTypeApi.createDatasetType(params)
      params.id = res
      params.children = []
      if (rootFlag.value) {
        emit('success', params)
      } else {
        actionNode.value.children.push(params)
      }
      message.success(t('common.createSuccess'))
    } else {
      await DatasetTypeApi.updateDatasetType(data)
      actionNode.value.name = data.name
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false

  } finally {
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    parentId: undefined,
    level: 1
  }
  formRef.value?.resetFields()
}
</script>